<template>
  <el-select
    v-model="selectedProductId"
    clearable
    filterable
    class="select-product"
    @change="handleChange"
  >
    <el-option
      v-for="product in productList"
      :key="product.id"
      :value="product.id"
      :label="product.name"
    />
  </el-select>
</template>

<script>
import { apiFindAllProducts } from './api'

export default {
  name: 'SelectProduct',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: Object, require: false, default: () => {
        return { id: '' }
      }
    }
  },
  data() {
    return {
      selectedProductId: '',
      productList: []
    }
  },
  watch: {
    value: {
      immediate: true,
      handler() {
        this.selectedProductId = this.value.id
      }
    }
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      this.findAllProducts()
    },
    async findAllProducts() {
      this.productList = await apiFindAllProducts()
    },
    handleReset() {
      this.selectedProductId = ''
      this.handleChange()
    },
    handleChange() {
      this.$emit('change', this.productList.find(product => product.id === this.selectedProductId) || { })
    }
  }
}
</script>

<style scoped lang="scss">
.select-product {
  width: vw(350px);
}
</style>
